<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-12-10
 * Time: 14:16
 */
namespace app\api\controller\v1;
use app\api\controller\BaseController;
use app\api\model\UserInvitation;
use app\api\model\UserMoney;
use app\api\model\UserTiMoneyOrder;
use app\api\service\UserPhone;
use app\api\service\UserToken;
use app\api\validate\PhoneGet;
use app\lib\exception\ParameterException;
use think\facade\Log;
use think\facade\Request;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\api\model\StoreUser as StoreUserModel;
use app\api\model\TeamUser as TeamUserModel;
use app\api\model\ProductOrder as ProductOrderModel;
use app\api\model\Store as StoreModel;

class User extends BaseController
{
    /**
     * 更新用户信息并返回用户最新信息
     * @http put
     * @url user
     */
    public function updateUser()
    {
        $uid = TokenService::getCurrentUid();
        $put = Request::put();
        $user = new UserModel();
        $userInfo = UserModel::get($uid);
        if($userInfo['status'] == 1){
            $user->allowField(true)->save([
                'nickname' => $put['nickname'],
                'head_img' => $put['head_img'],
                'province' => $put['province'],
                'status' => 2,
                'city' => $put['city'],
                'gender' => $put['gender']
            ],['id' => $uid]);
        } else {
            $user->allowField(true)->save([
                'nickname' => $put['nickname'],
                'head_img' => $put['head_img'],
                'province' => $put['province'],
                'city' => $put['city'],
                'gender' => $put['gender']
            ],['id' => $uid]);
        }
        $userChangeInfo = UserModel::get($uid);
        $userChangeInfo['all_money'] = UserMoney::where('user_id',$uid)->where('type',1)->sum('money');
        $userChangeInfo['ti_money'] = UserMoney::where('user_id',$uid)->where('type',2)->sum('money');
        return json(UserModel::get($uid),202);
    }

    /**
     * 更新用户二维码
     */
    public function setInviteImg()
    {
        $uid = TokenService::getCurrentUid();
        $userToken = new UserToken('code');
        $userToken->setCode($uid);
    }


    /**
     * 获取用户信息
     * @http get
     * @url user
     */
    public function getUserInfo()
    {
        $uid = TokenService::getCurrentUid();
        $info =  UserModel::get($uid);
        $info['all_money'] = UserMoney::where('user_id',$uid)->where('type',1)->sum('money');
        $info['ti_money'] = UserMoney::where('user_id',$uid)->where('type',2)->sum('money');
        $info['order'] = ProductOrderModel::where('user_id',$uid)->where('status','gt',1)->find();
        $userInvitation = UserInvitation::where('inviter',$uid)->select()->toArray();
        $user_ids = array_column($userInvitation,'invitee');
        $info['invite_num'] = UserModel::where('id','in',$user_ids)->where('status','eq',3)->count();
        $info['store'] = StoreModel::where('id','eq',$info['store_id'])->find();
        return $info;
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        $uid = TokenService::getCurrentUid();
        (new PhoneGet())->goCheck();
        $up = new UserPhone();
        $post = Request::post();
        $up->get($post);
        $userInfo = UserModel::where('id',$uid)->find();
        $userInfo['all_money'] = UserMoney::where('user_id',$uid)->where('type',1)->sum('money');
        $userInfo['ti_money'] = UserMoney::where('user_id',$uid)->where('type',2)->sum('money');
        return UserModel::get($uid);
    }

    /**
     * 绑定上下级
     *  下级没有下单重新绑定
     */
    public function createInvite()
    {
        $uid = TokenService::getCurrentUid();
        $userInfo = UserModel::get($uid);
        if($userInfo['type'] > 1) {
            return false;
        }
        $scene = Request::post('scene');
        $scene = explode("-",$scene);
        if($scene[0] == 'user') {
            $user = UserModel::where('id',$scene[1])->find();
            if($user){
                if($user['id'] != $uid){
                    $invite = UserInvitation::where('invitee', 'eq', $uid)
                        ->find();
                    if(!$invite) {
                        if($user['type']==1){
                            UserInvitation::create([
                                'inviter' => $user['id'],
                                'invitee' => $uid,
                                'type' => 1
                            ]);
                            UserModel::where('id',$uid)->update([
                                'store_id' => $user['store_id']
                            ]);
                        }elseif($user['type']==2 || $user['type']==3 || $user['type']==4){
                            $store = StoreUserModel::where('user_id',$scene[1])->find();
                            if($store){
                                if($store['user_id'] != $uid){
                                    UserInvitation::create([
                                        'inviter' => $store['id'],
                                        'invitee' => $uid,
                                        'type' => 2
                                    ]);
                                    UserModel::where('id',$uid)->update(['new_type' => 2, 'store_id'=>$store['store_id']]);
                                }
                            }
                        }elseif($user['type']==5||$user['type']==6){
                            $team = TeamUserModel::where('user_id',$scene[1])->find();
                            if($team){
                                if($team['user_id'] != $uid){
                                    UserInvitation::create([
                                        'inviter' => $team['id'],
                                        'invitee' => $uid,
                                        'type' => 3
                                    ]);
                                    UserModel::where('id',$uid)->update(['team_id'=>$team['team_id']]);
                                }
                            }
                        }
                    }else{
                        $orderCount = ProductOrderModel::where('user_id','eq',$uid)
                            ->where('status','gt',1)
                            ->count();
                        if($orderCount == 0) {
                            if($user['type']==1){
                                UserInvitation::where('id',$invite['id'])->update([
                                    'inviter' => $user['id'],
                                    'invitee' => $uid,
                                    'type' => 1
                                ]);
                            } elseif($user['type']==2||$user['type']==3||$user['type']==4){
                                $store = StoreUserModel::where('user_id',$scene[1])->find();
                                if($store){
                                    if($store['user_id'] != $uid){
                                        UserInvitation::where('id',$invite['id'])->update([
                                            'inviter' => $store['id'],
                                            'invitee' => $uid,
                                            'type' => 2
                                        ]);
                                        UserModel::where('id',$uid)->update(['new_type' => 2, 'store_id'=>$store['store_id']]);
                                    }
                                }
                            } elseif($user['type']==5||$user['type']==6){
                                $team = TeamUserModel::where('user_id',$scene[1])->find();
                                if($team){
                                    if($team['user_id'] != $uid){
                                        UserInvitation::where('id',$invite['id'])->update([
                                            'inviter' => $team['id'],
                                            'invitee' => $uid,
                                            'type' => 3
                                        ]);
                                        UserModel::where('id',$uid)->update(['team_id'=>$team['team_id']]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }elseif($scene[0] == 'storeUserOld'){
            $store = StoreUserModel::where('id',$scene[1])->find();
            if($store){
                if($store['user_id'] != $uid){
                    $invite = UserInvitation::where('invitee', 'eq', $uid)
                        ->find();
                    if(!$invite) {
                        UserInvitation::create([
                            'inviter' => $store['id'],
                            'invitee' => $uid,
                            'type' => 2
                        ]);
                        UserModel::where('id',$uid)->update(['new_type' => 2, 'store_id'=>$store['store_id']]);
                    }else{
                        $orderCount = ProductOrderModel::where('user_id','eq',$uid)
                            ->where('status','gt',1)
                            ->count();
                        if($orderCount == 0) {
                            UserInvitation::where('id',$invite['id'])->update([
                                'inviter' => $store['id'],
                                'invitee' => $uid,
                                'type' => 2
                            ]);
                            UserModel::where('id',$uid)->update(['new_type' => 2, 'store_id'=>$store['store_id']]);
                        }
                    }
                }
            }
        }elseif($scene[0] == 'storeUserNew'){
            $store = StoreUserModel::where('id',$scene[1])->find();
            if($store){
                if($store['user_id'] != $uid){
                    $invite = UserInvitation::where('invitee', 'eq', $uid)
                        ->find();
                    if(!$invite) {
                        UserInvitation::create([
                            'inviter' => $store['id'],
                            'invitee' => $uid,
                            'type' => 2
                        ]);
                        UserModel::where('id',$uid)->update(['store_id'=>$store['store_id']]);
                    }else{
                        $orderCount = ProductOrderModel::where('user_id','eq',$uid)
                            ->where('status','gt',1)
                            ->count();
                        if($orderCount == 0) {
                            UserInvitation::where('id',$invite['id'])->update([
                                'inviter' => $store['id'],
                                'invitee' => $uid,
                                'type' => 2
                            ]);
                            UserModel::where('id',$uid)->update(['store_id'=>$store['store_id']]);
                        }
                    }
                }
            }
        }elseif($scene[0] == 'teamUser') {
            $team = TeamUserModel::where('id',$scene[1])->find();
            if($team){
                if($team['user_id'] != $uid){
                    $invite = UserInvitation::where('invitee', 'eq', $uid)
                        ->find();
                    if(!$invite) {
                        UserInvitation::create([
                            'inviter' => $team['id'],
                            'invitee' => $uid,
                            'type' => 3
                        ]);
                        UserModel::where('id',$uid)->update(['team_id'=>$team['team_id']]);
                    }else{
                        $orderCount = ProductOrderModel::where('user_id','eq',$uid)
                            ->where('status','gt',1)
                            ->count();
                        if($orderCount == 0) {
                            UserInvitation::where('id',$invite['id'])->update([
                                'inviter' => $team['id'],
                                'invitee' => $uid,
                                'type' => 3
                            ]);
                            UserModel::where('id',$uid)->update(['team_id'=>$team['team_id']]);
                        }
                    }
                }
            }
        }

    }

    // 获取一级下级信息
    public function getInviteList()
    {
        $uid = TokenService::getCurrentUid();
        $list = UserInvitation::hasWhere('user',['status'=>1])
            ->where('user_invitation.inviter_id',$uid)
            ->with('user')
            ->order('user_invitation.id desc')->select()->toArray();
        if(count($list) > 0) {
            $user = [];
            foreach ($list as $k=>$v){
                $user[$k] = $v['user'];
            }
            return $user;
        }else {
            return [];
        }
    }


    // 进行提现操作
    public function createUserTiMoney($money)
    {
        Log::init([
            'type' => 'File'
        ]);
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if($money > 1) {
            if($money > $user['money']) {
                throw new ParameterException([
                    'msg' => [
                        '余额不足'
                    ]
                ]);
            }
        } else {
            throw new ParameterException([
                'msg' => [
                    '请输入正确的提现金额'
                ]
            ]);
        }
        $store = StoreModel::get($user['store_id']);
        if(!$store['start_day_num'] || !$store['end_day_num']) {
            throw new ParameterException([
                'msg' => [
                    '门店还未设置提现时间'
                ]
            ]);
        }
        $day = date('d');
        if($day >= $store['start_day_num'] && $day <= $store['end_day_num']) {
            $mode = UserTiMoneyOrder::create([
                'money' => $money,
                'user_id' => $uid,
                'order_id' => 0,
                'product_name' => date('Y-m-d').' 提现'
            ]);
            Log::write('提现用户:user_id='.$user['id'].'-nickname='.$user['nickname'].'-提现金额:'.$money.'-提现订单ID:'.$mode->id,'info');
            UserTiMoneyOrder::where('id',$mode->id)->update([
                'order_no' => 'u1shu2020'.$mode->id
            ]);
            $payMoney = new PayMoney();
            $status = $payMoney->addUserMoney('u1shu2020'.$mode->id);
            if($status) {
                return writeJson(201, [], '提现成功！');
            } else {
                throw new ParameterException([
                    'msg' => [
                        '提现失败'
                    ]
                ]);
            }
        } else{
            throw new ParameterException([
                'msg' => [
                    '未到门店提现时间'
                ]
            ]);
        }
    }
}